package com.common.base.app.extras

import android.os.Handler
import android.os.Looper
import android.view.View

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2024/6/13
 *
 * 描述：防重复点击拓展
 *
 * 修订历史：防抖
 *
 */
var lastClick = 0L
fun View.setSafeOnClickListener(timeInterval: Long = 400L, onSafeClick: (View) -> Unit) {

    setOnClickListener {
        if (System.currentTimeMillis() - lastClick >= timeInterval) {
            lastClick = System.currentTimeMillis()
            onSafeClick(this)
        }
    }
}

fun View.setOnClickListener(timeInterval: Long = 400L, onClick: View.OnClickListener) {
    this.setOnClickListener { view ->
        if (System.currentTimeMillis() - lastClick >= timeInterval) {
            lastClick = System.currentTimeMillis()
            onClick.onClick(view)
        }
    }
}

interface OnSafeClickListener : View.OnClickListener {

    val timeInterval: Long
        get() = 200L

    override fun onClick(v: View?) {
        if (System.currentTimeMillis() - lastClick >= timeInterval) {
            lastClick = System.currentTimeMillis()
            onSafeClick(v)
        }
    }

    fun onSafeClick(v: View?)
}

fun View.setSingleAndDoubleClickListener(
    timeInterval: Long = 400L,
    doubleClickTimeInterval: Long = 300L,
    onSingleClick: (View) -> Unit,
    onDoubleClick: (View) -> Unit
) {
    var lastClickTime = 0L
    var clickCount = 0

    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime < doubleClickTimeInterval) {
            // Detected double-click
            clickCount++
            if (clickCount == 2) {
                onDoubleClick(this)
                clickCount = 0
            }
        } else {
            // Reset count (for single-click)
            clickCount = 1
            // Post a delayed single-click action
            handler.postDelayed({
                if (clickCount == 1) {
                    onSingleClick(this)
                }
            }, timeInterval)
        }
        lastClickTime = currentTime
    }
}

fun View.setSingleAndDoubleClickListener(
    singleClickDelay: Long = 400L,
    onSingleClick: (View) -> Unit,
    onDoubleClick: (View) -> Unit
) {
    val handler = Handler(Looper.getMainLooper())
    var isSingleClick = true

    setOnClickListener {
        if (isSingleClick) {
            isSingleClick = false

            handler.postDelayed({
                if (!isSingleClick) {
                    isSingleClick = true
                    onSingleClick(this)
                }
            }, singleClickDelay)
        } else {
            isSingleClick = true
            onDoubleClick(this)
        }
    }
}